// The NSpring Framework for .NET
// Copyright (c) 2003, Jeffrey Varszegi
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without modification, 
// are permitted provided that the following conditions are met:
// 
// - Redistributions of source code must retain the above copyright notice, this 
// list of conditions and the following disclaimer.
// 
// - Redistributions in binary form must reproduce the above copyright notice, this 
// list of conditions and the following disclaimer in the documentation and/or other 
// materials provided with the distribution.
// 
// - Neither the name of the NSpring project nor the names of its contributors may 
// be used to endorse or promote products derived from this software without 
// specific prior written permission from the copyright owner.
// 
// - No product derived from this software may be called "NSpring", nor may 
// "NSpring" appear in the name of such a product, without specific prior written 
// permission from the copyright owner.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
// OF THE POSSIBILITY OF SUCH DAMAGE. 

namespace NSpring.Logging.Exceptions {

using System;
using System.Text;

using NSpring.Logging.Common;
using NSpring.Logging.EventFormatters;

/// <summary>
/// Converts LoggerException objects to string representations; may be used by 
/// IExceptionHandler instances
/// </summary>
public abstract class ExceptionFormatter {
    protected const string AMPERSAND                    = "&";
    protected const string APOSTROPHE                   = "'";
    protected const string BLANK_STRING                 = "";
    protected const string GREATER_THAN                 = ">";
    protected const string HYPHEN                       = "-";
    protected const string LESS_THAN                    = "<";
    protected const string QUOTE                        = "\"";
    protected const string SPACE                        = " ";
    protected const string UNDERSCORE                   = "_";
        
    protected const char COLON_CHAR                     = ':';
    protected const char HYPHEN_CHAR                    = '-';
    protected const char PERIOD_CHAR                    = '.';
    protected const char SPACE_CHAR                     = ' ';
    
    protected Encoding encoding                         = Encoding.UTF8;
    
    protected static string NEW_LINE                    = new string(new char[] {((char)13), ((char)10)});
    
    protected static string TIME_ZONE                   = DateTime.Now.ToString("zzz");
    
    protected static string[] dateStrings               = Constants.DateStrings;
    protected static string[] millisecondStrings        = Constants.MillisecondStrings;
    protected static string[] yearStrings               = Constants.YearStrings;

    private const int MAXIMUM_INITIAL_BUFFER_SIZE       = 8192;
    
    private int initialBufferSize                       = 1024;
    
    protected EventFormatter eventFormatter;
    
    private ExceptionFormatter() {}

    protected ExceptionFormatter(EventFormatter _eventFormatter) {
        if (_eventFormatter == null) {
            throw new ArgumentNullException();
        }
        eventFormatter = _eventFormatter;
    }
    
    public Encoding Encoding {
        get {
            return encoding;
        }
        set {
            if (value == null) {
                throw new ArgumentNullException();
            }
            encoding = value;
            eventFormatter.Encoding = encoding;
        }
    }
    
    public EventFormatter EventFormatter {
        get {
            return eventFormatter;
        }
    }
    
    /// <summary>
    /// Converts the specified LoggerException object to a string representation
    /// </summary>
    /// <param name="e">The LoggerException to format</param>
    /// <returns>A string representation of the LoggerException</returns>
    public string Format(LoggerException e) {
        StringBuilder sb = new StringBuilder(initialBufferSize);
        FormatExceptionHeader(e, sb);
        sb.Append(eventFormatter.Format(e.Event));
        FormatExceptionFooter(e, sb);
        string returnValue = sb.ToString();
        int length = returnValue.Length;
        if ((length > initialBufferSize) && (initialBufferSize < MAXIMUM_INITIAL_BUFFER_SIZE)) {
            length = Math.Min(length, MAXIMUM_INITIAL_BUFFER_SIZE);
            initialBufferSize = length;
        }
        return returnValue;
    }
    
    /// <summary>
    /// Each ExceptionFormatter relies on its EventFormatter to format each event
    /// received as part of a LoggerException; usually the event needs to be prepended
    /// and/or appended with other contextual information to be useful.  This method
    /// provides the formatted header information for the specified LoggerException,
    /// which may contain information related to the source logger, etc.
    /// </summary>
    /// <param name="e">The LoggerException for which to provide formatted header information</param>
    /// <param name="stringBuilder">The StringBuilder to which to append the formatted header information</param>
    protected abstract void FormatExceptionHeader(LoggerException e, StringBuilder stringBuilder);
    
    /// <summary>
    /// Each ExceptionFormatter relies on its EventFormatter to format each event
    /// received as part of a LoggerException; usually the event needs to be prepended
    /// and/or appended with other contextual information to be useful.  This method
    /// provides the formatted footer information for the specified LoggerException,
    /// which may contain information related to the source logger, etc.
    /// </summary>
    /// <param name="e">The LoggerException for which to provide formatted footer information</param>
    /// <param name="stringBuilder">The StringBuilder to which to append the formatted footer information</param>
    protected abstract void FormatExceptionFooter(LoggerException e, StringBuilder stringBuilder);
    
    /// <summary>
    /// In certain situations (such as logging many exceptions to a stream as XML) it is desirable
    /// to write a header and footer before and after the contents.  This method provides the header
    /// for such situations
    /// </summary>
    /// <returns>A string with which to begin a list of formatted LoggerExceptions</returns>
    public abstract string GetExceptionListHeader();
    
    /// <summary>
    /// In certain situations (such as logging many exceptions to a stream as XML) it is desirable
    /// to write a header and footer before and after the contents.  This method provides the footer
    /// for such situations
    /// </summary>
    /// <returns>A string with which to end a list of formatted LoggerExceptions</returns>
    public abstract string GetExceptionListFooter();
    
    public virtual void Initialize() {}
    
}

}
